<template>
  <div>
    <table
      border="1"
      width="700"
      style="border-collapse: collapse"
    >
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th>
            <label><input
                type="checkbox"
                v-model="isAll"
              /> <span>全选</span></label>
          </th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <Goods
          v-for="item in goodList"
          :key="item.name"
          :item="item"
          @del="delFn"
        ></Goods>
      </tbody>
      <tfoot>
        <tr v-if="goodList.length">
          <td>合计:</td>
          <td colspan="5">
            {{ totalPrice }}
          </td>
        </tr>
        <tr
          v-else
          style="text-align:center;"
        >
          <td colspan="6">
            购物车空空如也
          </td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
import Goods from "./components/Goods.vue";
export default {
  components: {
    Goods,
  },
  computed: {
    totalPrice() {
      return this.goodList.reduce((sum, item) => {
        // 选中状态累加
        if (item.checked) sum += item.price * item.num;
        // 返回累加结果
        return sum;
      }, 0);
    },
    isAll: {
      get() {
        return (
          this.goodList.length !== 0 &&
          this.goodList.every((v) => v.checked === true)
        );
      },
      set(val) {
        this.goodList.forEach((v) => (v.checked = val));
      },
    },
  },
  data() {
    return {
      goodList: [
        {
          name: "诸葛亮",
          price: 1000,
          num: 1,
          checked: false,
        },
        {
          name: "蔡文姬",
          price: 1500,
          num: 1,
          checked: false,
        },
        {
          name: "妲己",
          price: 2000,
          num: 1,
          checked: false,
        },
        {
          name: "鲁班",
          price: 2200,
          num: 1,
          checked: false,
        },
      ],
    };
  },
  methods: {
    delFn(theName) {
      this.goodList = this.goodList.filter((item) => item.name !== theName);
    },
  },
};
</script>

<style>
</style>